// React路由鉴权的实现方法
// https://www.jb51.net/article/169346.htm

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { getToken } from '@/utils/auth'

function generateRoute({ path, component: Component, redirectPath, children, isExact, requireAuth }) {
  if (children) {
    return (
      <React.Fragment>
        { children.map(item => generateRoute(item))}
      </React.Fragment>
    )
  }
  if (redirectPath) {
    return (
      <Redirect key={path} path="*" to={redirectPath} />
    )
  }
  return (
    <Route
      key={path}
      exact={isExact}
      path={path}
      render={props => {
        const isLogin = !!getToken()
        const Current = <Component {...props} />
        // console.log({ requireAuth, isLogin })
        if (!requireAuth) return Current
        if (!isLogin) return <Redirect from="path" to="/login" />
        return Current
      }} />
  )
}

export default function renderRoutes(list) {
  if (!list || !list.length) return ''
  const ls = list.map(item => generateRoute(item))
  return ls.filter(item => item)
}
